﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;

namespace S3.Common
{
    class LogHelper
    {
        public void WriteLog(string content)
        {            
            try
            {
                //Pass the file path and file name to the StreamReader constructor
                string pathLogFile = "Log.txt";
                var debugable = ConfigurationManager.AppSettings["EnableDebug"];
                if (File.Exists(pathLogFile) && Convert.ToBoolean(debugable.ToLower()) == true)
                {
                    var streamFile = File.Open(pathLogFile, FileMode.OpenOrCreate);
                    
                    StreamReader sr = new StreamReader(streamFile);

                    //Read the first line of text
                    String contentOld = sr.ReadToEnd();
                    StringBuilder contentNew = new StringBuilder();
                    contentNew.AppendLine(contentOld);
                    contentNew.AppendFormat("{0} - {1}", DateTime.Now, content);

                    //close the file
                    sr.Close();

                    var fs = new FileStream(pathLogFile, FileMode.Append);

                    if (fs.CanWrite)
                    {
                        StreamWriter sw = new StreamWriter(fs);
                        sw.Write(contentNew);
                        sw.Close();
                    }

                    fs.Close();
                }
                
            }
            catch (Exception e)
            {
                throw new Exception("Error when logging: " + e.Message);                
            }            
        }

        
    }
}
